package com.thesis.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.widget.Toast;

import com.thesis.object.Bill;
import com.thesis.object.Dish;
import com.thesis.object.FoodStatic;
import com.thesis.object.ListDishes;
import com.thesis.object.ListServeTableDetail;
import com.thesis.object.ListTable;
import com.thesis.object.ListUsers;
import com.thesis.object.Table;

public class Utils {

	Context context;
	private static Utils instance = null;

	public static void init() {
		if (instance == null) {
			instance = new Utils();
		}
	}

	public static Utils sharedInstance() {
		if (instance == null) {
			instance = new Utils();
		}
		return instance;
	}

	public String getNameManager(ListUsers list_users, int managerId) {

		for (int i = 0; i < list_users.getInstance().getListUser().size(); i++) {
			if (list_users.getInstance().getListUser().get(i).getId() == managerId)
				return list_users.getInstance().getListUser().get(i)
						.getLastName()
						+ " "
						+ list_users.getInstance().getListUser().get(i)
								.getFirstName();
		}

		return null;
	}

	public void showShortToast(Context context, String mess) {
		Toast.makeText(context, mess, Toast.LENGTH_SHORT).show();
	}

	public void sortByTurn(Context context, ArrayList<FoodStatic> in) {

		for (int i = 0; i < in.size(); i++) {
			for (int j = 0; j < in.size() - 1; j++) {
				if (in.get(j).getTurn() < in.get(j + 1).getTurn()) {
					FoodStatic a = new FoodStatic(in.get(j).getName(), in
							.get(j).getTurn(), in.get(j).getCost());
					in.set(j, in.get(j + 1));
					in.set(j + 1, a);
				}
			}
		}

	}

	public void sortByCost(Context context, ArrayList<FoodStatic> in) {

		for (int i = 0; i < in.size(); i++) {
			for (int j = 0; j < in.size() - 1; j++) {
				if (in.get(j).getCost() < in.get(j + 1).getCost()) {
					FoodStatic a = new FoodStatic(in.get(j).getName(), in
							.get(j).getTurn(), in.get(j).getCost());
					in.set(j, in.get(j + 1));
					in.set(j + 1, a);
				}
			}
		}

	}

	public ArrayList<Table> getListTableActive(ListTable listTable, int[] role) {
		ArrayList<Table> listTableActive = new ArrayList<Table>();
		for (int i = 0; i < listTable.getListTable().size(); i++) {
			if ((listTable.getListTable().get(i).getManagerId() == role[1] || listTable
					.getListTable().get(i).getManagerId() == role[2])
					&& listTable.getListTable().get(i).getStatusId() == 1) {
				listTableActive.add(listTable.getListTable().get(i));
			}
		}
		return listTableActive;
	}

	public ArrayList<Dish> getListFoodByTypeId(ListDishes list_dishes,
			int type_id) {
		ArrayList<Dish> result = new ArrayList<Dish>();
		for (int i = 0; i < list_dishes.getInstance().getListDishes().size(); i++) {
			if (list_dishes.getInstance().getListDishes().get(i).getTypeId() == type_id
					|| type_id == 0) {
				result.add(list_dishes.getInstance().getListDishes().get(i));
			}
		}

		return result;

	}

	public String convert(String s) {
		String temp = Normalizer.normalize(s, Normalizer.Form.NFD);
		Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
		return pattern.matcher(temp).replaceAll("");
	}



	public int getPosServe(int bill_id) {
		for (int i = 0; i < ListServeTableDetail.getInstance()
				.getListServeTableDetail().size(); i++) {
			if (ListServeTableDetail.getInstance().getListServeTableDetail()
					.get(i).getBill().getId() == bill_id) {
				return i;
			}
		}

		return -1;
	}

	public int getBillId(String table_name) {
		// Log.d("aaa11aa",""+ListServeTableDetail.getInstance().getListServeTableDetail().size()
		// );
		for (int i = 0; i < ListServeTableDetail.getInstance()
				.getListServeTableDetail().size(); i++) {
			if (ListServeTableDetail.getInstance().getListServeTableDetail()
					.get(i).getTable().getTableName().equals(table_name)) {
				// Log.d("bill_id",ListServeTableDetail.getInstance().getListServeTableDetail().get(i).getBill().getId()+"");
				return ListServeTableDetail.getInstance()
						.getListServeTableDetail().get(i).getBill().getId();
			}
		}
		return -1;
	}
	public Bill getBill(String table_name) {
		// Log.d("aaa11aa",""+ListServeTableDetail.getInstance().getListServeTableDetail().size()
		// );
		for (int i = 0; i < ListServeTableDetail.getInstance()
				.getListServeTableDetail().size(); i++) {
			if (ListServeTableDetail.getInstance().getListServeTableDetail()
					.get(i).getTable().getTableName().equals(table_name)) {
				// Log.d("bill_id",ListServeTableDetail.getInstance().getListServeTableDetail().get(i).getBill().getId()+"");
				return ListServeTableDetail.getInstance()
						.getListServeTableDetail().get(i).getBill();
			}
		}
		return null;
	}
	public boolean unpackZip(String path, String zipname)
	{       
	     InputStream is;
	     ZipInputStream zis;
	     try 
	     {
	         String filename;
	         is = new FileInputStream(path + zipname);
	         zis = new ZipInputStream(new BufferedInputStream(is));          
	         ZipEntry ze;
	         byte[] buffer = new byte[1024];
	         int count;

	         while ((ze = zis.getNextEntry()) != null) 
	         {
	             // zapis do souboru
	             filename = ze.getName();

	             // Need to create directories if not exists, or
	             // it will generate an Exception...
	             if (ze.isDirectory()) {
	                File fmd = new File(path + filename);
	                fmd.mkdirs();
	                continue;
	             }

	             FileOutputStream fout = new FileOutputStream(path + filename);

	             // cteni zipu a zapis
	             while ((count = zis.read(buffer)) != -1) 
	             {
	                 fout.write(buffer, 0, count);             
	             }

	             fout.close();               
	             zis.closeEntry();
	         }

	         zis.close();
	     } 
	     catch(IOException e)
	     {
	         e.printStackTrace();
	         return false;
	     }

	    return true;
	}	
	
	public void showDialog(Context context, int title, int message, int icon, int negButName,
			OnClickListener negButListener, int posButName, OnClickListener posButListener) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);

		builder.setTitle(title).setMessage(message).setNegativeButton(negButName, negButListener)
				.setPositiveButton(posButName, posButListener).setIcon(icon);
		builder.create().show();
	}
	
	public boolean isHaveinBill (Dish dish , Bill bill){
		for (int i = 0 ; i< bill.getListDishDes().getListBill().size();i++){
			if(dish.getId() == bill.getListDishDes().getListBill().get(i).getFoodId()){
				return true;
			}
			
		}

		return false;
	}
	
	public String getNameofFood(int id_food){
		for (int i = 0 ; i < ListDishes.getInstance().getListDishes().size();i++){
			if (ListDishes.getInstance().getListDishes().get(i).getId() == id_food){
				return ListDishes.getInstance().getListDishes().get(i).getName();
			}
			
		}
		return null;
	}
	
	public String sha1Hash( String toHash )
	{
	    String hash = null;
	    try
	    {
	        MessageDigest digest = MessageDigest.getInstance( "SHA-1" );
	        byte[] bytes = toHash.getBytes("UTF-8");
	        digest.update(bytes, 0, bytes.length);
	        bytes = digest.digest();
	        StringBuilder sb = new StringBuilder();
	        for( byte b : bytes )
	        {
	            sb.append( String.format("%02X", b) );
	        }
	        hash = sb.toString();
	    }
	    catch( NoSuchAlgorithmException e )
	    {
	        e.printStackTrace();
	    }
	    catch( UnsupportedEncodingException e )
	    {
	        e.printStackTrace();
	    }
	    return hash;
	}
	
	public int parseJsonDish(String data){
		ListDishes.getInstance().clear();
		JSONObject json;
		try {
			json = new JSONObject(data);
			JSONArray listDishesArray = json.getJSONArray("info");

			ListDishes listDishes = ListDishes.getInstance();

			listDishes.addDishByJson(listDishesArray);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

		return ListDishes.getInstance().getListDishes().size();
	}
}
